<script setup lang="ts">
import type { IP, Subnet } from '@/apis/model/ip.ts'
import type { FormInstance } from '@arco-design/web-vue'
import { getBandwidthTypeListApi } from '@/apis/modules/bandwidthType'
import { getComputeIpSubnetListApi } from '@/apis/modules/computedIp'
import { addIpApi, updateIpApi } from '@/apis/modules/ip.ts'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'

interface IEmit {
  (e: 'success'): void
}

interface IProps {
  record?: IP
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()

const visible = defineModel<boolean>({ required: true })

const { parse } = useLangField()
const { allRegionOptions } = useRegions()

const formRef = ref<FormInstance>()
const formRules = {
  region_id: [{ required: true, message: '请选择区域' }],
  bandwidth_type: [{ required: true, message: '请选择带宽类型' }],
  network_name: [{ required: true, message: '请选择网络' }],
  subnet: [{ required: true, message: '请选择子网' }],
  ips: [{ required: true, message: '请输入IP地址' }],
}
const formData = ref({
  id: undefined,
  region_id: '',
  bandwidth_type: '',
  network_name: '',
  subnet: '',
  ips: '',
})

const bandwidthTypes = ref<LabelValue[]>([])
const networks = ref<(LabelValue & { subnets: Subnet[] })[]>([])
const subnets = computed<Subnet[]>(() => {
  return (
    networks.value.find(item => item.value === formData.value.network_name)
      ?.subnets || []
  )
})
const currentSubnet = computed(() => {
  return subnets.value.find(item => item.uuid === formData.value.subnet)
})

function handleRegionChange() {
  formData.value.bandwidth_type = ''
  formData.value.network_name = ''
  formData.value.subnet = ''
  getBandwidthTypes()
  getNetworks()
}

function handleNetworkChange() {
  formData.value.subnet = ''
}

async function getBandwidthTypes() {
  const res = await getBandwidthTypeListApi({
    region_id: formData.value.region_id,
  })
  bandwidthTypes.value = (res.list || []).map((item) => {
    const name = parse(item.name || '')
    return { label: name?.['zh-CN'] || '-', value: item.id! }
  })
}

async function getNetworks() {
  const res = await getComputeIpSubnetListApi({
    region_id: formData.value.region_id,
  })
  networks.value = (res.list || []).map((item) => {
    return { label: item.name!, value: item.uuid!, subnets: item.subnet! }
  })
  console.log(networks.value)
}

async function handleSubmit() {
  const err = await formRef.value.validate()
  if (err) {
    return false
  }
  const fn = props.record ? updateIpApi : addIpApi
  try {
    const data = props.record
      ? { ...omit(formData.value, ['ips']), ip: formData.value.ips }
      : { ...formData.value }
    await fn(data)
    Message.success(props.record ? '编辑成功' : '新建成功')
    emit('success')
    return true
  } catch (err) {
    console.log(err)
    return false
  }
}

function handleOpen() {
  if (!props.record) {
    return
  }
  formData.value = {
    id: props.record.id as any,
    region_id: props.record.region_id!,
    bandwidth_type: props.record.bandwidth_type! as any,
    network_name: props.record.network_name!,
    subnet: props.record.subnet!,
    ips: props.record.ip!,
  }
  getBandwidthTypes()
  getNetworks()
}

function handleClose() {
  formRef.value.resetFields()
}
</script>

<template>
  <a-modal
    v-model:visible="visible"
    width="480px"
    :title="record ? '编辑 IP' : '新建 IP'"
    :on-before-ok="handleSubmit"
    :mask-closable="false"
    @before-open="handleOpen"
    @close="handleClose"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item
        label="所属区域"
        field="region_id"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <a-select
          v-model="formData.region_id"
          placeholder="请选择区域"
          :options="allRegionOptions"
          @change="handleRegionChange"
        />
      </a-form-item>
      <a-form-item
        label="带宽类型"
        field="bandwidth_type"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <a-select
          v-model="formData.bandwidth_type"
          placeholder="请选择带宽类型"
          :options="bandwidthTypes"
          :disabled="!formData.region_id"
        />
      </a-form-item>
      <a-form-item
        label="网络名称"
        field="network_name"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <a-select
          v-model="formData.network_name"
          placeholder="请选择网络"
          :options="networks"
          :disabled="!formData.region_id"
          @change="handleNetworkChange"
        />
      </a-form-item>
      <a-form-item
        label="子网名称"
        field="subnet"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <a-select
          v-model="formData.subnet"
          placeholder="请选择子网"
          :field-names="{ label: 'name', value: 'uuid' }"
          :options="subnets"
          :disabled="!formData.network_name"
        />
        <template
          v-if="currentSubnet"
          #extra
        >
          <div>
            <div>子网网段：{{ currentSubnet.cidr }}</div>
            <div class="flex items-center space-x-1">
              <span>IP 范围：{{ currentSubnet.address_pool![0].start }}-{{
                currentSubnet.address_pool![0].end
              }}</span>
              <a-popover
                v-if="currentSubnet.address_pool!.length > 1"
                position="bottom"
              >
                <i-icons-more-circle
                  class="translate-y--1px cursor-pointer hover:text-color-primary"
                />
                <template #content>
                  <div class="max-h-280px flex flex-col overflow-auto">
                    <div
                      v-for="(item, index) in currentSubnet.address_pool"
                      :key="index"
                      class="mb-1.5 border-b pb-1.5 text-xs last:mb-0 last:border-b-none last:pb-0"
                    >
                      {{ item.start }}-{{ item.end }}
                    </div>
                  </div>
                </template>
              </a-popover>
            </div>
          </div>
        </template>
      </a-form-item>
      <a-form-item
        label="IP 地址"
        field="ips"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <a-textarea
          v-if="!record"
          v-model.trim="formData.ips"
          class="h-[200px]"
          placeholder="请输入 IP 或 IP 段，换行分隔，最多500个
IP 段示例192.168.10.1-192.168.10.24"
        />
        <a-input
          v-else
          v-model.trim="formData.ips"
          placeholder="请输入IP地址"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
